﻿using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Newtonsoft.Json;
using Microsoft.Extensions.Caching.Memory;
using Zero.WebAPI.Framework.ConfigModel;
using Zero.WebAPI.Framework.Config.Helper;
using Zero.WebAPI.Framework.Helper.Encrypt;
using Zero.WebAPI.Framework.Security.Model;
using System.IdentityModel.Tokens.Jwt;

namespace Zero.WebAPI.Framework.Filter
{
    public class AuthInterceptor : IActionFilter
    {
        public static APIWhiteList APIWhiteList { get; private set; }
        private readonly IMemoryCache memoryCache;

        static AuthInterceptor()
        {
            APIWhiteList = ConfigHelper.GetSection<APIWhiteList>("APIWhiteList");
        }

        public AuthInterceptor(IMemoryCache memoryCache)
        {
            this.memoryCache = memoryCache;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            ActionDescriptor actionDescriptor = context.ActionDescriptor;
            if (!(actionDescriptor is ControllerActionDescriptor))
                return;
            ControllerActionDescriptor? descriptor = actionDescriptor as ControllerActionDescriptor;

            // 白名单比对
            string? apiPath = context.HttpContext.Request.Path.Value;
            if (APIWhiteList.Match(apiPath))
                return;

            AllowAnonymousAttribute? allowAnonymous = descriptor.MethodInfo.GetCustomAttribute<AllowAnonymousAttribute>();
            if(allowAnonymous != null)
            {
                return;
            }
            else
            {
                if (!context.HttpContext.Request.Headers.ContainsKey("Authorization"))
                {
                    context.Result = new UnauthorizedResult();
                    return;
                }
                string authStr = context.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ","");
                // 解析token
                JwtSecurityToken jwtSecurityToken = JwtHelper.ParseToken2(authStr);
                Identity user = new Identity();
                Identity.SetUserInfo(user,jwtSecurityToken);
                // 添加用户信息到当前的请求上下文中
                context.HttpContext.Items["user"] = user;
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
    }
}
